package com.tchy.cloud.controller;


import com.tchy.cloud.entity.CPlatformEntity;
import com.tchy.cloud.tools.ChinaInitial;
import com.tchy.cloud.tools.CipherUtil;
import com.tchy.cloud.tools.Tools;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 分平台信息
 */
@Controller
@RequestMapping("/platformController")
public class CPlatformController {
    private static final Logger logger = Logger.getLogger(CPlatformController.class.getName());

    @Autowired
    private CommonService commonService;

    /**
     * 分平台数据列表展示页面跳转
     *
     * @return
     */
    @RequestMapping(params = "index")
    public ModelAndView index() {
        return new ModelAndView("clound/platform/index");
    }

    @RequestMapping(params = "selectList")
    public ModelAndView selectList() {
        return new ModelAndView("clound/platform/selectList");
    }


    /**
     * 分平台数据列表数据
     *
     * @param platformEntity
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(CPlatformEntity platformEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CPlatformEntity.class, dataGrid);
        cq.addOrder("platformId", SortDirection.desc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, platformEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 分平台数据列表数据
     *
     * @param platformEntity
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "select_datagrid")
    public void select_datagrid(CPlatformEntity platformEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CPlatformEntity.class, dataGrid);

        cq.eq("open", 1);
        cq.addOrder("platformId", SortDirection.desc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, platformEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 新增或编辑页面跳转
     *
     * @param platformEntity
     * @param req
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(CPlatformEntity platformEntity, HttpServletRequest req) {
        if (platformEntity.getPlatformId() != null) {
            platformEntity = commonService.getEntity(CPlatformEntity.class, platformEntity.getPlatformId());
        } else {
            platformEntity.setPlatformCode(Tools.getRandomNum());//8为随机数
        }
        req.setAttribute("entity", platformEntity);
        return new ModelAndView("clound/platform/addorupdate");
    }


    /**
     * 新增及修改的数据处理
     *
     * @param platformEntity
     * @return
     */
    @RequestMapping(params = "saveorupdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveorupdate(CPlatformEntity platformEntity) {
        AjaxJson j = new AjaxJson();
        String name = platformEntity.getName();
        try {
            if (platformEntity.getPlatformId() != null) {//修改操作
                CPlatformEntity entity = commonService.get(CPlatformEntity.class, platformEntity.getPlatformId());
                if (!platformEntity.getName().equals(entity.getName())) {//名称改变
                    String sql = "select * from c_platform where name = ? and platform_id != ?";
                    List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{name, platformEntity.getPlatformId()});
                    if (!list.isEmpty()) {//数据库存在相同名称
                        j.setMsg("分平台名字重复，请修改后再试。");
                    } else {//数据库不存在相同名称
                        String platformCode = entity.getPlatformCode();//code
                        String platformkey = CipherUtil.getMd5(ChinaInitial.getPYIndexStr(name, true));//名字首字母
                        String platformSecret = CipherUtil.getMd5(platformkey + platformCode);//加密后key+code
                        platformEntity.setPlatformCode(platformCode);
                        platformEntity.setPlatformkey(platformkey);
                        platformEntity.setPlatformSecret(platformSecret);
                        MyBeanUtils.copyBeanNotNull2Bean(platformEntity, entity);
                        commonService.saveOrUpdate(entity);
                        j.setMsg("操作成功");
                    }
                } else {//名称没有改变
                    MyBeanUtils.copyBeanNotNull2Bean(platformEntity, entity);
                    commonService.saveOrUpdate(entity);
                    j.setMsg("操作成功");
                }

            } else {//保存操作
                String sql = "select * from c_platform where name = ?";
                List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{name});
                if (!list.isEmpty()) {
                    j.setMsg("分平台名字重复，请修改后再试。");
                } else {
                    String platformCode = Tools.getRandomNum();//8为随机数
                    String platformkey = CipherUtil.getMd5(ChinaInitial.getPYIndexStr(name, true));//名字首字母
                    String platformSecret = CipherUtil.getMd5(platformkey + platformCode);//加密后key+code
                    platformEntity.setPlatformCode(platformCode);
                    platformEntity.setPlatformkey(platformkey);
                    platformEntity.setPlatformSecret(platformSecret);
                    commonService.save(platformEntity);
                    j.setMsg("操作成功");
                }
            }
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }


    /**
     * 验证选项名称是否存在，存在不允许提交
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "checkName")
    @ResponseBody
    public Map<String, String> checkName(HttpServletRequest request) {
        String id = request.getParameter("id");//问题主键
        String name = request.getParameter("name");//问题名称
        Map<String, String> map = new HashMap<>();
        try {
            if (id != "") {//修改操作
                CPlatformEntity entity = commonService.getEntity(CPlatformEntity.class, Integer.valueOf(id));
                if (!name.equals(entity.getName())) {
                    String sql = "select count(*) num from c_platform where name= ? and platform_id != ?";
                    List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{name, Integer.valueOf(id)});
                    Map returnMmap = list.get(0);
                    if (Integer.valueOf(String.valueOf(returnMmap.get("num"))) == 0) {
                        map.put("code", "0");
                        map.put("msg", "success");
                    } else {
                        map.put("code", "1");
                        map.put("msg", "此平台名称已经存在，请更改后重试。");
                    }
                }

            } else {//保存操作
                String sql = "select count(*) num from c_platform where name= ?";
                List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{name});
                Map returnMmap = list.get(0);
                if (Integer.valueOf(String.valueOf(returnMmap.get("num"))) == 0) {
                    map.put("code", "0");
                    map.put("msg", "success");
                } else {
                    map.put("code", "1");
                    map.put("msg", "此平台名称已经存在，请更改后重试。");
                }

            }
        } catch (Exception e) {
            logger.error(e);
        }
        return map;
    }


    /**
     * 删除
     *
     * @param platformEntity
     * @return
     */
    @RequestMapping(params = "del", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson del(CPlatformEntity platformEntity) {
        AjaxJson j = new AjaxJson();
        try {
            if (platformEntity.getPlatformId() != null) {//删除
                CPlatformEntity entity = commonService.get(CPlatformEntity.class, platformEntity.getPlatformId());
                commonService.delete(entity);
                j.setMsg("操作成功");
            } else {//主键不存在
                j.setMsg("分平台不存在，请重试。");
            }

        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }


    /**
     * 禁用或者开通
     *
     * @param platformEntity
     * @return
     */
    @RequestMapping(params = "stop_or_start", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson stop_or_start(CPlatformEntity platformEntity) {
        AjaxJson j = new AjaxJson();
        try {
            if (platformEntity.getPlatformId() != null) {
                CPlatformEntity entity = commonService.get(CPlatformEntity.class, platformEntity.getPlatformId());
                if (entity.getOpen() == 0)
                    entity.setOpen(1);
                else
                    entity.setOpen(0);
                commonService.saveOrUpdate(entity);
                j.setMsg("操作成功");
            } else {//主键不存在
                j.setMsg("分平台不存在，请重试。");
            }

        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }
}







